package cn.com.eado.crm.v.fragment


import android.os.SystemClock
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import cn.com.eado.crm.R
import cn.com.eado.crm.app.KEY_FIRST
import cn.com.eado.crm.app.KEY_USER_ID
import cn.com.eado.crm.app.KEY_USER_NAME
import cn.com.eado.crm.app.MyApp
import cn.com.eado.crm.app.extenstion.hide
import cn.com.eado.crm.app.extenstion.show
import cn.com.eado.crm.app.extenstion.toast
import cn.com.eado.crm.app.utils.GsonUtil
import cn.com.eado.crm.app.utils.SpUtil
import cn.com.eado.crm.databinding.FragmentLoginBinding
import cn.com.eado.crm.m.db.*
import cn.com.eado.crm.model.LoadStatus
import cn.com.eado.preado.app.utils.autoCleared
import cn.com.eado.preado.viewmodel.LoginViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_login.*
import kotlin.concurrent.thread

/**
 * A simple [Fragment] subclass.
 */
class LoginFragment : BaseBindingFragment<FragmentLoginBinding>(R.layout.fragment_login) {

    private var vm by autoCleared<LoginViewModel>()

    override fun initTheFragment() {
        initConfig()
        initView()
        initViewModel()
        initBinding()
    }

    private fun initConfig() {
        if (!SpUtil.readBoolean(MyApp.instance, KEY_FIRST, false)){
            SpUtil.writeBoolean(MyApp.instance, KEY_FIRST, true)
            initIcon()
            initDb()
        }
    }

    private fun initIcon(){
        thread{
            val list = listOf<AppIcon>(
                AppIcon(0, 0, "客户管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "片区信息", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "客户集团信息管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "行业信息管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "企业信息管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "设计院信息管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "竞争对手管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "产品管理", R.drawable.ic_dashboard_black_24dp, false, false),
                //
                AppIcon(0, 0, "销售管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "挖掘列表", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "项目挖掘", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "个人报备", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "审核报备", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "报备列表", R.drawable.ic_dashboard_black_24dp, false, false),
                //
                AppIcon(0, 0, "日常业务", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "个人周报", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "周报查看", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "个人月报", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "月报查看", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "管理事务", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "请路会杂", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "查阅跟踪信息", R.drawable.ic_dashboard_black_24dp, false, false),
                //
                AppIcon(0, 0, "系统设置", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "系统日志", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "系统模块", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "角色管理", R.drawable.ic_dashboard_black_24dp, false, false),
                AppIcon(0, 0, "用户管理", R.drawable.ic_dashboard_black_24dp, false, false)
                )
            MyDatabase.getInstance().appIconDao().insertAll(list)
        }
    }

    private fun initDb(){
        val list1 = GsonUtil.getListFromAssetsJson<Province>("city.json", activity, object: TypeToken<List<Province>>(){}.type)
        Log.e("tag", "Province size = ${list1.size}")
        val list2 = GsonUtil.getListFromAssetsJson<Area>("area.json", activity, object: TypeToken<List<Area>>(){}.type)
        Log.e("tag", "Area size = ${list2.size}")
        val list3 = GsonUtil.getListFromAssetsJson<Client>("client.json", activity, object: TypeToken<List<Client>>(){}.type)
        Log.e("tag", "Client size = ${list3.size}")
        val list4 = GsonUtil.getListFromAssetsJson<HangYe>("hangye.json", activity, object: TypeToken<List<HangYe>>(){}.type)
        Log.e("tag", "HangYe size = ${list4.size}")
        val list5 = GsonUtil.getListFromAssetsJson<Track>("track.json", activity, object: TypeToken<List<Track>>(){}.type)
        Log.e("tag", "Track size = ${list5.size}")
        val list6 = GsonUtil.getListFromAssetsJson<Urgent>("urgent.json", activity, object: TypeToken<List<Urgent>>(){}.type)
        Log.e("tag", "Urgent size = ${list6.size}")
        val list7 = GsonUtil.getListFromAssetsJson<XingZhi>("xingzhi.json", activity, object: TypeToken<List<XingZhi>>(){}.type)
        Log.e("tag", "XingZhi size = ${list7.size}")
        thread {
            MyDatabase.getInstance().provinceDao().insertAll(list1)
            MyDatabase.getInstance().areaDao().insertAll(list2)
            MyDatabase.getInstance().clientDao().insertAll(list3)
            MyDatabase.getInstance().hangYeDao().insertAll(list4)
            MyDatabase.getInstance().trackDao().insertAll(list5)
            MyDatabase.getInstance().urgentDao().insertAll(list6)
            MyDatabase.getInstance().xingZhiDao().insertAll(list7)
        }
    }

    private fun initView() {
        bt.setOnClickListener { login() }
    }

    private fun initViewModel() {
        vm = ViewModelProviders.of(this).get(LoginViewModel::class.java)
        vm.loginResult.observe(this, Observer {
            if (it.status == LoadStatus.SUCCESS){
                bt.isEnabled = false
                progressBar1.hide(activity)
                activity?.toast(it.data)
                thread {
                    if (it.data != null && !it.data.contains("错误")){  //login success
                        if(MyDatabase.getInstance().accountDao().queryWithName(vm.name) == null){
                            MyDatabase.getInstance().accountDao().insert(Account(0, vm.name, vm.pwd, false))
                        }
                        val account = MyDatabase.getInstance().accountDao().queryWithName(vm.name)
                        if(account != null){
                            SpUtil.writeString(MyApp.instance, KEY_USER_NAME, account.name)
                            SpUtil.writeInt(MyApp.instance, KEY_USER_ID, account.id)
                        }
                    }
                    SystemClock.sleep(2000)
                    activity?.runOnUiThread {
                        if (it.data != null && !it.data.contains("错误")){
                            Navigation.findNavController(view!!).navigate(R.id.action_loginFragment_to_homeFragment)
                        }
                    }
                }
            }else if (it.status == LoadStatus.ERROR){
                bt.isEnabled = true
                progressBar1.hide(activity)
                activity?.toast(it.data)
            }
        })
    }

    private fun initBinding() {
        //
    }

    private fun login(){
        val name = etName.text.trim().toString()
        val pwd = etPwd.text.trim().toString()
        if (name.isEmpty() || pwd.isEmpty()){
            activity?.toast("input can not be empty")
            return
        }
        vm.name = name
        vm.pwd = pwd
        vm.setLogin(true)
        progressBar1.show(activity)
    }

}
